package org.nw.web.sys;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;

import org.apache.commons.lang.StringUtils;
import org.nw.service.IToftService;
import org.nw.service.sys.RoleService;
import org.nw.vo.ParamVO;
import org.nw.vo.TreeVO;
import org.nw.vo.sys.RoleVO;
import org.nw.web.AbsToftController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 角色管理
 * 
 * @author xuqc
 * @date 2012-6-10 下午03:38:27
 */
@Controller
@RequestMapping(value = "/role")
public class RoleController extends AbsToftController {

	@Autowired
	private RoleService roleService;

	@Override
	public IToftService getService() {
		// 这里事务使用spring自动管理，service必须从springbean管理器中取得
		return roleService;
	}

	@RequestMapping(value = "/loadPowerFun.json")
	@ResponseBody
	public List<TreeVO> loadPowerFun(HttpServletRequest request, HttpServletResponse response) {
		String pk_role = request.getParameter("pk_role");
		if(StringUtils.isBlank(pk_role)) {
			throw new RuntimeException("请先选择一个角色!");
		}
		return roleService.loadPowerFunTree(pk_role);
	}

	@RequestMapping(value = "/savePowerFun.json")
	@ResponseBody
	public Map<String, Object> savePowerFun(HttpServletRequest request, HttpServletResponse response) {
		String pk_role = request.getParameter("pk_role");
		if(StringUtils.isBlank(pk_role)) {
			throw new RuntimeException("请先选择一个角色!");
		}
		String[] pkFunAry = request.getParameterValues("pk_fun");
		roleService.savePowerFun(pk_role, pkFunAry);
		return this.genAjaxResponse(true, null, null);
	}

	@Override
	protected void checkBeforeSave(AggregatedValueObject billVO, ParamVO paramVO) {
		CircularlyAccessibleValueObject parentVO = billVO.getParentVO();
		Object role_code = parentVO.getAttributeValue("role_code");
		if(role_code == null) {
			throw new RuntimeException("编码不能为空！");
		}
		try {
			RoleVO roleVO = roleService.getByRole_code(role_code.toString());
			if(StringUtils.isBlank(parentVO.getPrimaryKey())) {
				// 新增的情况
				if(roleVO != null) {
					throw new RuntimeException("编码已经存在！");
				}
			} else {
				// 修改的情况
				if(roleVO != null) {
					if(!parentVO.getPrimaryKey().equals(roleVO.getPk_role())) {
						throw new RuntimeException("编码已经存在！");
					}
				}
			}
		} catch(BusinessException e) {
			e.printStackTrace();
		}
	}
}
